package cn.shyouchi.wuguanjia.android.ui.meetting.apply;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.meet.MeetApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.ui.meetting.common.MeetPerson;
import cn.shyouchi.wuguanjia.android.ui.meetting.common.MeetRoom;
import cn.shyouchi.wuguanjia.android.ui.meetting.common.SelMeetPersonActivity;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import cn.shyouchi.wuguanjia.android.widget.dialog.TimePickerDialogFragment;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static cn.shyouchi.wuguanjia.android.ui.meetting.common.SelMeetPersonActivity.REQ_CODE_DEPARTMENT;
import static cn.shyouchi.wuguanjia.android.ui.meetting.common.SelMeetPersonActivity.RES_CODE_SUCCESS;

public class ApplyMeetActivity extends BaseActivity {

    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.et_meet_name)
    EditText mEtMeetName;
    @BindView(R.id.tv_start_time)
    TextView mTvStartTime;
    @BindView(R.id.tv_end_time)
    TextView mTvEndTime;
    @BindView(R.id.tv_holder)
    TextView mTvHolder;
    @BindView(R.id.person_info_next1)
    ImageView mPersonInfoNext1;
    @BindView(R.id.et_meet_purpose)
    EditText mEtMeetPurpose;

    MeetApi mMeetApi;

    MenuItem mSubMenuItem;

    List<MeetRoom> mMeetRooms = new ArrayList<>();
    MeetRoom mMeetRoom;

    @Override
    public int initContentView() {
        return R.layout.activity_apply_meet;
    }

    @Override
    public void initInjector() {
        mMeetApi = new MeetApi(mContext);
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setTitle(getTitle().toString());
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        setSupportActionBar(mTopBar.getToolbar());

        mTvHolder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mMeetRooms.isEmpty()) {
                    showSelDialog("选择会议室", mMeetRooms);
                } else {
                    ToastUtil.showToast("没有会议室");
                }
            }
        });
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    @OnClick({R.id.tv_start_time, R.id.tv_end_time})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_start_time:
                showTimePicker((TextView) view, "选择开始时间");
                break;
            case R.id.tv_end_time:
                showTimePicker((TextView) view, "选择结束时间");
                break;
        }
    }


    private void fetchMeetRoom(String startTime, String endTime) {
        Map<String, Object> params = new HashMap<>();
        params.put("start", startTime);
        params.put("end", endTime);
        mMeetApi.fetchMeetRoom(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<BaseRequestResult<List<MeetRoom>>>(mContext) {
                    @Override
                    public void onNext(BaseRequestResult<List<MeetRoom>> listBaseRequestResult) {
                        mMeetRooms.clear();
                        mMeetRooms.addAll(listBaseRequestResult.getResultMessage());
                    }
                });
    }


    public void showTimePicker(final TextView tv, String title) {
        TimePickerDialogFragment mTimePickerDialog;
        mTimePickerDialog = new TimePickerDialogFragment(getSupportFragmentManager(), title, "");
        mTimePickerDialog.setOnTimePickedListener(new TimePickerDialogFragment.onTimePickedListener() {
            @Override
            public void onPicked(String time) {
                mTvHolder.setText("");
                mMeetRoom = null;
                tv.setText(time);
                if (!TextUtils.isEmpty(mTvStartTime.getText()) && !TextUtils.isEmpty(mTvEndTime.getText())) {
                    fetchMeetRoom(mTvStartTime.getText().toString(), mTvEndTime.getText().toString());
                }
            }
        });
        mTimePickerDialog.showWhitDate();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        mSubMenuItem = menu.add("提交");
        mSubMenuItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item == mSubMenuItem) {
            if (judgeData()) {
                Intent intent = new Intent(mContext, SelMeetPersonActivity.class);
                intent.putExtra("single", true);
                intent.putExtra("selDepartment", true);
                startActivityForResult(intent, REQ_CODE_DEPARTMENT);
            }
        }
        return super.onOptionsItemSelected(item);
    }

    private boolean judgeData() {

        if (TextUtils.isEmpty(mEtMeetName.getText().toString())) {
            ToastUtil.showToast("请填写会议名");
            return false;
        }


        if (TextUtils.isEmpty(mEtMeetPurpose.getText().toString())) {
            ToastUtil.showToast("请填写会议目的");
            return false;
        }


        if (TextUtils.isEmpty(mTvStartTime.getText().toString())) {
            ToastUtil.showToast("请选择开始时间");
            return false;
        }

        if (TextUtils.isEmpty(mTvEndTime.getText().toString())) {
            ToastUtil.showToast("请选择结束时间");
            return false;
        }

        if (mMeetRoom == null) {
            ToastUtil.showToast("请选择会议室");
            return false;
        }
        return true;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_CODE_DEPARTMENT && resultCode == RES_CODE_SUCCESS) {
            MeetPerson department = data.getParcelableExtra("data");
            if (department != null) {
                submitData(department.getId());
            }
        }
    }

    private void submitData(int deId) {

        Map<String, Object> params = new HashMap<>();
        params.put("name", mEtMeetName.getText().toString());
        params.put("meeting_room_id", mMeetRoom.getId());
        params.put("start", mTvStartTime.getText());
        params.put("end", mTvEndTime.getText());
        params.put("detail", mEtMeetPurpose.getText().toString());
        params.put("department_id", deId);

        mMeetApi.meetAplly(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<BaseRequestResult<String>>(mContext) {
                    @Override
                    public void onNext(BaseRequestResult<String> stringBaseRequestResult) {
                        ToastUtil.showToast(stringBaseRequestResult.getResultMessage());
                        finish();
                    }
                });



    }


    private synchronized void showSelDialog(String title, List<MeetRoom> sels) {

        List<String> rooms = new ArrayList<>();
        for (MeetRoom r : sels) {
            rooms.add(r.getName());
        }

        final String[] choices = rooms.toArray(new String[rooms.size()]);
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
        TextView tvTitle = (TextView) getLayoutInflater().inflate(R.layout.dialog_title, null);
        tvTitle.setText(title);
        builder.setCustomTitle(tvTitle);
        builder.setItems(choices, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mMeetRoom = mMeetRooms.get(which);
                mTvHolder.setText(mMeetRoom.getName());
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }
}
